import React, { useState, useEffect } from 'react'
import { useAuth, useSubscription } from '../contexts/AuthProvider'
import { usePapers } from '../hooks/usePapers'
import { StatsCard } from '../components/dashboard/StatsCard'
import { RecommendationSection } from '../components/dashboard/RecommendationSection'
import { ActivityFeed } from '../components/dashboard/ActivityFeed'
import { QuickActions } from '../components/dashboard/QuickActions'
import { Button } from '../components/ui/Button'
import { 
  BookOpen, 
  TrendingUp, 
  Bell, 
  Calendar,
  Sparkles,
  ArrowRight,
  Settings
} from 'lucide-react'

export function Dashboard() {
  const { userProfile } = useAuth()
  const { subscription} = useSubscription()
  const { 
    papers: recommendations, 
    loading: loadingPapers,
    fetchPersonalizedPapers 
  } = usePapers()

  const [stats, setStats] = useState({
    totalSaved: 0,
    readToday: 0,
    weeklyGoal: 5,
    goalProgress: 0
  })

  useEffect(() => {
    if (userProfile?.paper_preferences?.categories?.length) {
      fetchPersonalizedPapers()
    }
  }, [userProfile?.paper_preferences, fetchPersonalizedPapers])

  useEffect(() => {
    // Load user stats
    const loadStats = async () => {
      // This would come from the API
      setStats({
        totalSaved: subscription?.usage_metrics?.saved_papers_count || 0,
        readToday: 3, // Mock data
        weeklyGoal: 5,
        goalProgress: 60
      })
    }
    loadStats()
  }, [subscription])

  const getGreeting = () => {
    const hour = new Date().getHours()
    if (hour < 12) return 'Good morning'
    if (hour < 18) return 'Good afternoon'
    return 'Good evening'
  }

  const hasPreferences = (userProfile?.paper_preferences?.categories?.length || 0) > 0

  if (!hasPreferences) {
    return (
      <div className="text-center py-12">
        <Sparkles className="h-12 w-12 mx-auto mb-4 text-gray-400" />
        <h2 className="text-2xl font-bold text-gray-900 mb-2">Welcome to ArXiv+!</h2>
        <p className="text-gray-600 mb-8 max-w-md mx-auto">
          Let's personalize your research experience by setting up your interests and preferences.
        </p>
        <Button 
          size="lg"
          onClick={() => window.location.href = '/app/onboarding'}
        >
          <Settings className="h-4 w-4 mr-2" />
          Complete Setup
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Welcome Header */}
      <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">
              {getGreeting()}, {userProfile?.display_name || userProfile?.full_name}!
            </h1>
            <p className="text-gray-600">
              Ready to discover new research? Here's what's trending in your field.
            </p>
          </div>
          <div className="hidden md:block">
            <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
              <Sparkles className="h-8 w-8 text-white" />
            </div>
          </div>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatsCard
          title="Papers Saved"
          value={stats.totalSaved}
          icon={<BookOpen className="h-5 w-5" />}
          trend="+12% from last week"
          color="blue"
        />
        <StatsCard
          title="Read Today"
          value={stats.readToday}
          icon={<TrendingUp className="h-5 w-5" />}
          trend={`${stats.readToday}/${stats.weeklyGoal} weekly goal`}
          color="green"
        />
        <StatsCard
          title="Active Alerts"
          value={subscription?.usage_metrics?.active_alerts_count || 0}
          icon={<Bell className="h-5 w-5" />}
          trend="2 new matches today"
          color="purple"
        />
        <StatsCard
          title="Reading Streak"
          value="7 days"
          icon={<Calendar className="h-5 w-5" />}
          trend="Personal best!"
          color="orange"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-8">
          {/* Personalized Recommendations */}
          <RecommendationSection 
            papers={recommendations}
            loading={loadingPapers}
            onRefresh={fetchPersonalizedPapers}
          />

          {/* Quick Actions */}
          <QuickActions />
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Reading Goal Progress */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-900">Weekly Reading Goal</h3>
              <span className="text-sm text-gray-500">{stats.readToday}/{stats.weeklyGoal}</span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2 mb-4">
              <div 
                className="bg-green-500 h-2 rounded-full transition-all duration-300"
                style={{ width: `${stats.goalProgress}%` }}
              />
            </div>
            <p className="text-sm text-gray-600">
              Great progress! You're {stats.weeklyGoal - stats.readToday} papers away from your weekly goal.
            </p>
          </div>

          {/* Activity Feed */}
          <ActivityFeed />

          {/* Upgrade CTA for free users */}
          {userProfile?.subscription_status === 'free' && (
            <div className="bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg p-6 text-white">
              <h3 className="font-bold text-lg mb-2">Unlock Premium Features</h3>
              <p className="text-blue-100 mb-4 text-sm">
                Get unlimited saves, advanced analytics, and priority alerts.
              </p>
              <Button 
                variant="secondary"
                size="sm"
                className="w-full"
                onClick={() => window.location.href = '/app/subscription'}
              >
                Upgrade Now <ArrowRight className="h-4 w-4 ml-2" />
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}